package com.fun.crazyThread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by han.yuan
 * 2018/4/7
 * Lock的小例子
 */
public class LockTest {
    private Lock lock=new ReentrantLock();
    public  void testLock1(Thread thread){
        //先获取锁
        lock.lock();
        try {
           System.out.println("线程"+thread.getName()+"获取了当前锁");
            Thread.sleep(2000);
        }catch (Exception e){
            System.out.println("线程"+thread.getName()+"发生异常");
        }finally {
            System.out.println("线程"+thread.getName()+"释放了当前锁");
            lock.unlock();
        }
    }

    public void testTryLock(Thread thread){
        if (lock.tryLock()){
            try {
                System.out.println("线程"+thread.getName()+"尝试获取了当前锁");
                Thread.sleep(2000);
            }catch (Exception e){
                System.out.println("线程"+thread.getName()+"发生异常");
            }finally {
                System.out.println("线程"+thread.getName()+"释放了当前锁");
                lock.unlock();
            }
        }else{
            System.out.println("我是线程:"+Thread.currentThread().getName()+" 当前锁被别人占用，无法获取锁");
        }
    }

    public void testTryLockParam(Thread thread) throws InterruptedException {
        if (lock.tryLock(3000, TimeUnit.MILLISECONDS)){
            try {
                System.out.println("线程"+thread.getName()+"在3秒钟内获取了当前锁");
                Thread.sleep(2000);
            }catch (Exception e){
                System.out.println("线程"+thread.getName()+"发生异常");
            }finally {
                System.out.println("线程"+thread.getName()+"释放了当前锁");
                lock.unlock();
            }
        }else{
            System.out.println("我是线程:"+Thread.currentThread().getName()+" 当前锁被别人占用，3秒后无法获取锁");
        }
    }

    public static void main(String[] args){
        LockTest lockTest=new LockTest();
        Thread t1=new Thread(new Runnable() {
            @Override
            public void run() {
                //lockTest.testLock1(Thread.currentThread());
                //lockTest.testTryLock(Thread.currentThread());
                try {
                    lockTest.testTryLockParam(Thread.currentThread());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t1");
        Thread t2=new Thread(new Runnable() {
            @Override
            public void run() {
                //lockTest.testLock1(Thread.currentThread());
                //lockTest.testTryLock(Thread.currentThread());
                try {
                    lockTest.testTryLockParam(Thread.currentThread());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t2");
        t1.start();
        t2.start();
    }
}
